package com.hongxun.design.utils.wifiutil;

import android.content.Context;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import com.hongxun.design.MyApp;
import com.hongxun.design.activitys.FaceSendAndReceiveActivity;
import com.hongxun.design.mytools.MyLog;
import com.hongxun.design.object_properties.Global;

/**
 * Created by zerdoor_pc on 2016/4/18.
 * wifi热点的创建/检测/关闭
 */
public class WifiHostUtil {
    private static WifiHostUtil instance = null;
    private Context context;
    public static WifiManager mWifimanager;

    WifiHostUtil(Context context) {
        this.context = context;
        if (mWifimanager == null) {
            mWifimanager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        }
    }

    // 检测Wifi是否打开
    public boolean wifiIsOpen() {
        if (mWifimanager == null) {
            mWifimanager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        }
        return mWifimanager.isWifiEnabled();
    }

    public void openWifi() {
        MyLog.L(MyApp.AppName + "into OpenWifi()");
        if (mWifimanager == null) {
            mWifimanager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        }
        if (!mWifimanager.isWifiEnabled()) {
            mWifimanager.setWifiEnabled(true);
        }
        MyLog.L(MyApp.AppName + "out OpenWifi()");
    }

    public static WifiHostUtil getInstance(Context context) {

        if (instance == null) {
            instance = new WifiHostUtil(context);
        }
        instance.context = context;
        return instance;
    }

    public void startWifiHost(String wifiName) {
        closeWifi();
        //检查wifi开关
        if (!mWifimanager.isWifiEnabled()) {
            mWifimanager.setWifiEnabled(true);
        }
        mWifimanager.setWifiEnabled(false);
        stratWifiAp(wifiName);
    }

    // 启动一个wifi热点
    private boolean stratWifiAp(String wifiName) {
        MyLog.L(MyApp.AppName + "stratWifiAp启动一个Wifi热点！");
        Method method1 = null;
        boolean ret = false;
        try {
            method1 = mWifimanager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
//			WifiConfiguration apConfig =CreateWifiInfo(wifiName, Global.PASSWORD,3);// createPassHotWifiConfig(wifiName, Global.PASSWORD);
            WifiConfiguration apConfig = createPassHotWifiConfig(wifiName, Global.PASSWORD);
            ret = (Boolean) method1.invoke(mWifimanager, apConfig, true);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            MyLog.D(MyApp.AppName + "stratWifiAp() IllegalArgumentException e");
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            MyLog.D(MyApp.AppName + "stratWifiAp() IllegalAccessException e");
        } catch (InvocationTargetException e) {
            e.printStackTrace();
            MyLog.D(MyApp.AppName + "stratWifiAp() InvocationTargetException e");
        } catch (SecurityException e) {
            e.printStackTrace();
            MyLog.D(MyApp.AppName + "stratWifiAp() SecurityException e");
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
            MyLog.D(MyApp.AppName + "stratWifiAp() NoSuchMethodException e");
        }
        MyLog.L(MyApp.AppName + "out startWifiAp 启动一个Wifi 热点！");
        ((FaceSendAndReceiveActivity) context).startService();
        return ret;
    }

    // wep密码保护 config.wepKeys[0] = "" + mPasswd + ""; 是关键
    private WifiConfiguration createPassHotWifiConfig(String mSSID, String mPasswd) {
        MyLog.L(MyApp.AppName + "out createPassHotWifiConfig（） 新建一个Wifi配置！ SSID =" + mSSID + " password =" + mPasswd);
        WifiConfiguration config = new WifiConfiguration();
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();
        config.SSID = mSSID;
        config.wepKeys[0] = mPasswd;
        config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
        config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
        config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
        config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
        config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
        config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        config.wepTxKeyIndex = 0;
        config.priority = 0;

        MyLog.L(MyApp.AppName + "out createPassHotWifiConfig（） 启动一个Wifi配置！ config.SSID=" + config.SSID + "password =" + config.wepKeys[0]);
        return config;
    }

    /**
     * 关闭wifi热点
     */
    public void closeWifi() {
        if (mWifimanager != null) closeWifiAp(mWifimanager);
    }

    public boolean closeWifiAp(WifiManager wifiManager) {

        MyLog.L(MyApp.AppName + "into closeWifiAp（） 关闭一个Wifi 热点！");
        boolean ret = false;
        if (isWifiApEnabled(wifiManager)) {
            try {
                Method method = wifiManager.getClass().getMethod("getWifiApConfiguration");
                method.setAccessible(true);
                WifiConfiguration config = (WifiConfiguration) method.invoke(wifiManager);
                Method method2 = wifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
                ret = (Boolean) method2.invoke(wifiManager, config, false);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
        MyLog.L(MyApp.AppName + "out closeWifiAp（） 关闭一个Wifi 热点！");
        return ret;
    }

    /**
     * 检测wifi热点是否可用
     */
    public boolean isWifiApEnabled(WifiManager wifiManager) {
        try {
            Method method = wifiManager.getClass().getMethod("isWifiApEnabled");
            method.setAccessible(true);
            return (Boolean) method.invoke(wifiManager);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
